import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/api/special_list.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_detail_by_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_new_dict_all_entity.dart';
import 'package:get/get.dart';

///主题树状
class SelectThemeTreeController extends GetxController {
  /// 请求参数
  Map<String, dynamic> queryParameters = {};

  /// 组织数据
  List<GetNewDictAllEntity> treeList = [];

  /// 选中的节点
  GetNewDictAllEntity selectedEntity = GetNewDictAllEntity();

  /// 初始化数据列表 教育培训主题
  Future<void> onInitData() async {
    if (treeList.isEmpty) {
      // 请求接口
      final result = await SpecialListApis.getNewDictionaryDataByTree(dictionaryType: 'jypxzt_q1uSZQaD').execute();
      result.onSuccess((value) {
        if (value.data != null) {
          final List<GetNewDictAllEntity> treeLists = value.data!;
          getDetailById(treeLists);
        }
      });
    }
  }
  /// 点击节点
  Future<void> clickOnNode(GetNewDictAllEntity treeEntity) async {
    treeEntity.isExpand = !treeEntity.isExpand!;
    selectedEntity = treeEntity;
    update();
  }

  List<GetDetailByIdSurveyTypes> surveyTypes = [];

  ///调查问卷详情
  void getDetailById(List<GetNewDictAllEntity> treeLists) async {
    queryParameters['id'] = Get.arguments['id']; //id
    final res = await HttpUtil()
        .generateGetRequest<GetDetailByIdEntity>(
          Interface.getDetailById,
          queryParameters: queryParameters,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        final GetDetailByIdEntity dataSelect = result.data!;
        surveyTypes = dataSelect.surveyTypes ?? [];
        traverseTreeList(treeLists);
        treeList = treeLists;
      }
    });
    update();
  }

  void traverseTreeList(List<GetNewDictAllEntity> nodeList) {
    for (var node in nodeList) {
      node.isExpand = true;
      for (var value in surveyTypes) {
        if (value.surveyTypeDicId == node.id) {
          //选择了当前对象 设置展开选中
          node.isChecked = true;
        }
      }
      traverseTree(node);
    }
  }

  void traverseTree(GetNewDictAllEntity node) {
    if (node.dictionaryDetails!.isNotEmpty) {
      traverseTreeList(node.dictionaryDetails!);
    }
  }
}
